package com.example.leetcode.trainingcamp.week9.sunday;

/**
 * 给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
 *
 * 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
 *
 * 此外，你可以假设该网格的四条边均被水包围。
 *
 *  
 *
 * 示例 1：
 *
 * 输入：grid = [
 *   ["1","1","1","1","0"],
 *   ["1","1","0","1","0"],
 *   ["1","1","0","0","0"],
 *   ["0","0","0","0","0"]
 * ]
 * 输出：1
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/number-of-islands
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Test200 {

    private boolean[][] visit;

    private int len;

    private int width;


    public int numIslands(char[][] grid) {
        int[][] t = {{-1,0},{1,0},{0,-1},{0,1}};
        len = grid.length;
        width = grid[0].length;
        visit = new boolean[len][width];
        int count = 0;
        for (int i = 0;i<len;i++){
            for (int j = 0;j<width;j++){
                if (!visit[i][j] && grid[i][j] == '1') {
                    count++;
                    dfs(grid,i,j,t);
                }
            }
        }
        return count;
    }

    public void dfs(char[][] grid,int r,int c,int[][] t){
        if (grid[r][c] == 0) return;
        for (int[] t1: t) {
            int nR = r + t1[0];
            int nC = c + t1[1];
            if (nR>=0 && nR<len && nC>=0 && nC<width && !visit[nR][nC] && grid[nR][nC] == '1'){
                visit[nR][nC] = true;
                dfs(grid,nR,nC,t);
            }
        }
    }
}


class Demo200{
    public static void main(String[] args) {
        char[][] grid = {{'1','1','0','0','0'},{'1','1','0','0','0'},{'0','0','1','0','0'},{'0','0','0','1','1'}};
        Test200 t = new Test200();
        System.out.println(t.numIslands(grid));
    }
}